<template>
    <base-breadcrumb>
        <template>
            <a-card class="mb20" :loading="loading.LOADING">
                <div>
                    <a-steps progress-dot :current="1" size="small">
                        <a-step title="步骤一" description="基本信息填写" />
                        <!-- <a-step title="步骤二" description="各部门填写资料" /> -->
                        <a-step title="步骤二" description="资料汇总" />
                        <a-step title="完成" description="上传签字盖章后的资料" />
                    </a-steps>
                </div>

                <titleName title="基本信息" class="title-style"></titleName>
                <a-form-model
                    ref="ruleForm"
                    :model="form"
                    :rules="rules"
                    :labelCol="{ lg: { span: 6 }, sm: { span: 6 } }"
                    :wrapperCol="{ lg: { span: 16 }, sm: { span: 16 } }"
                >
                    <a-row :gutter="24">
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="所属分公司：">
                                <BaseInput disabled placeholder="请选择" v-model="form.branchComName"></BaseInput>
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="所属项目：">
                                <BaseInput disabled placeholder="请选择" v-model="form.projectName"></BaseInput>
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="分包商名称：">
                                <BaseInput disabled placeholder="请选择" v-model="form.subContractorName"></BaseInput>
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="名称：" prop="name">
                                <BaseInput disabled placeholder="请输入名称" v-model="form.name" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="截止2016年4月30日累计含税金额(元)" prop="yearAmount">
                                <BaseInputNumber :min="0" placeholder="请输入" v-model="form.yearAmount" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="8" :sm="8">
                            <a-form-model-item label="计量月份">
                                <BaseInput disabled placeholder="请输入" v-model="form.measureMonth" />
                            </a-form-model-item>
                        </a-col>
                        <a-col :md="24" :sm="24">
                            <a-form-model-item label="施工范围：">
                                <BaseTextarea disabled placeholder="请输入" v-model="form.constructionRange" />
                            </a-form-model-item>
                        </a-col>

                        <!-- <a-col :md="8" :sm="8">
                            <a-form-model-item label="a.至上月累计金额（含税）(元)：">
                                <BaseInputNumber
                                    :min="0"
                                    disabled
                                    placeholder="请输入"
                                    v-model="form.toLastMonthCumulativeAmount"
                                />
                            </a-form-model-item>
                        </a-col> -->
                        <a-col :md="24" :sm="24" class="mb-24">
                            <a-table
                                :columns="columns"
                                :data-source="form.workloadDetailDTO"
                                size="middle"
                                bordered
                                :pagination="false"
                            >
                                <template
                                    v-for="col in ['amountExTax', 'tax']"
                                    :slot="col"
                                    slot-scope="text, record, index"
                                >
                                    <div :key="col">
                                        <a-input-number
                                            v-if="index < 2"
                                            style="
                                                border-color: #e4ac0b;
                                                background-color: #fff9e8;
                                                margin: -5px 0;
                                                width: 100%;
                                            "
                                            :value="text"
                                            :min="0"
                                            placeholder="请输入"
                                            @change="(e) => handleChange(e, record.key, col)"
                                        />
                                        <template v-else>{{ text ? text : '0' }}</template>
                                    </div>
                                </template>
                                <template slot="remark" slot-scope="text, record">
                                    <BaseInput placeholder="请输入" v-model="record.remark"></BaseInput>
                                </template>
                            </a-table>
                        </a-col>
                        <!-- <a-col :md="24" :sm="24">
                            <a-form-model-item label="a+b.至本月累计金额（含税）(元)">
                                <BaseInput disabled placeholder="a+b.至本月累计金额（含税）(元)" v-model="form.total" />
                            </a-form-model-item>
                        </a-col> -->

                        <a-col :md="16" :sm="6">
                            <a-form-model-item label="附件上传">
                                <l-table
                                    v-if="isUpdate"
                                    @fileArrysData="fileArrysData"
                                    :uploadArrys="form.fileInfoVOList"
                                    businessCode="BM05"
                                ></l-table>
                            </a-form-model-item>
                        </a-col>
                    </a-row>
                </a-form-model>
            </a-card>

            <div class="tool-btns mb20 page-btn-right-top">
                <a-button
                    :loading="loading.DELETE"
                    v-if="form.auditStatus == 'DRAFT'"
                    type="danger"
                    @click="deleteDraft"
                    >删除草稿</a-button
                >
                <a-button :loading="loading.DRAFT" type="primary" @click="submitForm('DRAFT')">保存草稿</a-button>
                <a-button :loading="loading.SUBMITTED" type="primary" @click="submitForm('SUBMITTED')">提交</a-button>
                <a-button type="primary" @click="closeForm">关闭</a-button>
            </div>
        </template>
    </base-breadcrumb>
</template>
<script>
import { getStepOneDetail, getTable, addStepThree, updateStepThree, delStepThree } from '@/api/businessAffairs/sml'
// import { length } from 'store/storages/all'
import { isAttachment } from '@/utils/util'
const columns = [
    {
        title: '项目/金额',
        dataIndex: 'name',
        scopedSlots: { customRender: 'project_amount' },
    },
    {
        title: '1、不含增值税金额(元)',
        dataIndex: 'amountExTax',
        scopedSlots: { customRender: 'amountExTax' },
    },
    {
        title: '2、增值税(元)',
        dataIndex: 'tax',
        scopedSlots: { customRender: 'tax' },
    },
    {
        title: '含增值税（1+2）(元)',
        dataIndex: 'totalOf',
        scopedSlots: { customRender: 'totalOf' },
    },
    {
        title: '备注',
        dataIndex: 'remark',
        scopedSlots: { customRender: 'remark' },
    },
]

export default {
    name:'a'+Date.now(),
    data() {
        this.columns = columns
        return {
            form: {
                total: 0,
            },

            loading: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                LOADING: false,
            },
            rules: {
                yearAmount: [{ required: true, message: '截止2016年4月30日累计含税金额(元)' }],
                completePart: [{ required: true, message: '分包上报完成形象部位' }],
            },
            dataSource: [],
            id: '',
            isUpdate: true,
        }
    },
    mounted() {
        if (this.$route.query.id) {
            this.id = this.$route.query.id
            console.log(this.id)
            this.isUpdate = false
            this.getStepOneDetail()
        }
    },
    methods: {
        fileArrysData: function (val) {
            this.form.fileInfoVOList = val
            console.log(val)
        },
        getStepOneDetail() {
            let params = {
                id: this.id,
            }
            this.loading.LOADING = true
            getStepOneDetail(params).then((res) => {
                this.loading.LOADING = false
                this.isUpdate = true
                if (res.data.workloadDetailDTO) {
                    res.data.workloadDetailDTO.forEach((item, idx) => {
                        item.key = idx.toString()
                    })
                }

                this.form = res.data

                if (this.form.workloadDetailDTO == null || this.form.workloadDetailDTO.length == 0) {
                    this.getTable()
                }
            })
        },
        getTable() {
            let params = {
                type: '3',
            }
            getTable(params).then((res) => {
                console.log(res)
                res.data.forEach((item, idx) => {
                    item.key = idx.toString()
                    item.remark = ''
                    item.workloadTypeId = item.id
                    item.id = ''
                    if (idx != 2) {
                        item.amountExTax = ''
                        item.tax = ''
                        item.totalOf = 0
                    }
                })
                this.form.workloadDetailDTO = res.data
                this.changeInput()
            })
        },
        // 删除草稿
        deleteDraft() {
            let params = {
                id: this.form.id,
            }
            let that = this
            this.$confirm({
                title: '温馨提示',
                content: '确定是否删除数据？',
                okText: '确认',
                okType: 'danger',
                cancelText: '取消',
                onOk() {
                    return delStepThree(params).then((res) => {
                        if (res.data.code == '200') {
                            that.$message.success('操作成功')
                            that.closeForm()
                        }
                    })
                },
                onCancel() {},
            })
        },
        validWorkloadDetailDTO(list) {
            let flag = false
            list.forEach((i) => {
                console.log(i)
                if (i.amountExTax === '' || i.tax === '') {
                    this.$message.info('请完善本月完成工作量表格')
                    flag = true
                }
            })
            return flag
        },
        // 提交表单
        submitForm(auditStatus) {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    if (isAttachment(this, auditStatus, this.form.fileInfoVOList)) return
                    if (this.validWorkloadDetailDTO(this.form.workloadDetailDTO)) {
                        return
                    }
                    this.loading[auditStatus] = true
                    if (this.form.auditStatus == null) {
                        this.form.auditStatus = auditStatus
                        this.form.auditStatus = auditStatus

                        this.form.measureId = this.id
                        this.form.id = ''
                        addStepThree(this.form).then((res) => {
                            this.loading[auditStatus] = false
                            this.$message.success('操作成功')
                            this.closeForm()
                        })
                    } else {
                        this.form.auditStatus = auditStatus

                        updateStepThree(this.form).then((res) => {
                            this.loading[auditStatus] = false
                            this.$message.success('操作成功')
                            this.closeForm()
                        })
                    }
                } else {
                  this.$message.warning("请填写完所有必填项信息")
                }
            })
        },
        // 关闭表单
        closeForm() {
            this.$multiTab.close(this.$route.fullpath)
        },

        handleChange(value, key, column) {
            const newData = [...this.form.workloadDetailDTO]
            const target = newData.filter((item) => key === item.key)[0]

            if (target) {
                target[column] = value
                target[column] = value == null ? '' : parseFloat(value)
                target.totalOf = Number(((parseFloat(target.amountExTax) || 0) + (parseFloat(target.tax) || 0)).toFixed(2))
                //     ;['amountExTax', 'tax', 'totalOf'].forEach((i) => {
                //         newData[newData.length - 3][i] = newData
                //             .reduce((total, item, index) => {
                //                 let isLast = index == newData.length - 3
                //                 return isLast ? total : (parseFloat(total[i] || total) || 0) + (parseFloat(item[i]) || 0)
                //             })
                //             .toFixed(2)
                //     })
                this.form.workloadDetailDTO = newData
            }
            this.changeInput()
            console.log(this.form)
        },
        changeInput() {
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 1].amountExTax = 0
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 1].tax = 0
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 1].totalOf = 0
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 3].amountExTax = 0
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 3].tax = 0
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 3].totalOf = 0
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 1].amountExTax = this.sum(
                this.form.workloadDetailDTO,
                'amountExTax'
            )
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 1].tax = this.sum(
                this.form.workloadDetailDTO,
                'tax'
            )
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 1].totalOf = this.sum(
                this.form.workloadDetailDTO,
                'totalOf'
            )
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 3].amountExTax = this.sumIndex(
                this.form.workloadDetailDTO,
                'amountExTax'
            )
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 3].tax = this.sumIndex(
                this.form.workloadDetailDTO,
                'tax'
            )
            this.form.workloadDetailDTO[this.form.workloadDetailDTO.length - 3].totalOf = this.sumIndex(
                this.form.workloadDetailDTO,
                'totalOf'
            )
        },
        sumIndex(arr, str) {
            let sum = 0
            for (let i = 0; i < arr.length; i++) {
                if (i < 3) {
                    sum += Number(parseFloat(arr[i][str] || 0).toFixed(2))
                }
            }
            console.log(sum)
            return sum
        },
        sum(arr, str) {
            let sum = 0
            for (let i = 0; i < arr.length; i++) {
                if (i != 2) {
                    sum += Number(parseFloat(arr[i][str] || 0).toFixed(2))
                }
            }
            console.log(sum)
            return sum
        },
    },
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.tool-btns {
    display: flex;
    justify-content: flex-end;
    @{deep} .ant-btn + .ant-btn {
        margin-left: 12px;
    }
}
.step-text {
    .ant-steps-item-title {
        width: 168px;
    }
}
.f-col {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    text-align: left;
    .ant-form-item-label {
        text-align: left;
    }
}
.check-box {
    .ant-checkbox-group {
        margin-top: 1.5%;
        display: flex;
        justify-content: space-between;
    }
    .ant-checkbox-group-item {
        position: static !important;
    }
}
.radio-box {
    .ant-radio-wrapper {
        position: static !important;
    }
    .ant-radio-group {
        margin-top: 3% !important;
        display: flex;
    }
}
.mb-24 {
    padding-left: 24px;
    margin-bottom: 24px;
}
.tx-center {
    text-align: center;
}
h4 {
    text-align: center;
}
.foot-btn {
    display: flex;
    justify-content: flex-end;
}
</style>
